package com.eian.boot.rabbit.core.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.support.ListenerExecutionFailedException;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.ErrorHandler;

@Slf4j
@Component
public class ConsumerErrorHandler implements ErrorHandler {

    private final MessageRecoverer messageRecoverer;

    public ConsumerErrorHandler(MessageRecoverer messageRecoverer) {
        this.messageRecoverer = messageRecoverer;
    }

    @Override
    public void handleError(@NonNull Throwable t) {
        if (t instanceof ListenerExecutionFailedException ex) {
            Message message = (Message) ex.getFailedMessage();
            if (shouldRetry(message)) {
                log.warn("消息重试: {}", message);
                messageRecoverer.recover(message, ex);
            } else {
                log.error("消息的最大重试次数已超过: {}", message, t);
                sendToDlx(message);
            }
        } else {
            log.error("监听器中发生意外错误", t);
        }
    }

    private boolean shouldRetry(Message message) {
        // 实现根据消息重试次数判断逻辑
        return true;
    }

    private void sendToDlx(Message message) {
        // 实现死信队列发送逻辑
    }
}